package ch.jamme.util;

import org.apache.commons.logging.*;

public class Logger {

	public static final int DEBUG = 1;
	public static final int INFO = 2;
	public static final int WARN = 3;
	public static final int ERROR = 4;
	public static final int FATAL = 5;

	public static final int SYSTEM_OUT = 10;

	private Logger() {}

	public static void log(Object sender, int level, Object message, Throwable t) {
		if (level >= SYSTEM_OUT) {
			System.out.println(message);
			level -= SYSTEM_OUT;
		}
		if (level == 0) return;

		if (sender == null) sender = Logger.class;
		Log logger = getLog(sender);
		String msg = message == null ? "" : message.toString();
		switch (level) {
			case DEBUG:
				if (t == null) logger.debug(msg);
				else
					logger.debug(msg, t);
				break;
			case INFO:
				if (t == null) logger.info(msg);
				else
					logger.info(msg, t);
				break;
			case WARN:
				if (t == null) logger.warn(msg);
				else
					logger.warn(msg, t);
				break;
			case ERROR:
				if (t == null) logger.error(msg);
				else
					logger.error(msg, t);
				break;
			case FATAL:
				if (t == null) logger.fatal(msg);
				else
					logger.fatal(msg, t);
				break;
		}
	}

	public static void log(Object sender, int level, Object message) {
		log(sender, level, message, null);
	}

	public static void log(Object sender, Throwable t, boolean isIgnored) {
		log(sender, t, isIgnored ? WARN : ERROR);
	}

	public static void log(Object sender, Throwable t, int level) {
		String exceptionMessage = t.getLocalizedMessage();
		if (exceptionMessage == null) exceptionMessage = t.getMessage();
		log(sender, level, exceptionMessage, t);
	}

	public static void info(Object sender, String message) {
		log(sender, INFO, message, null);
	}

	public static void info(Object sender, String message, Throwable t) {
		log(sender, INFO, message, t);
	}

	public static void warn(Object sender, String message) {
		log(sender, WARN, message, null);
	}

	public static void warn(Object sender, String message, Throwable t) {
		log(sender, WARN, message, t);
	}

	public static void error(Object sender, String message) {
		log(sender, ERROR, message, null);
	}

	public static void error(Object sender, String message, Throwable t) {
		log(sender, ERROR, message, t);
	}

	public static void debug(Object sender, String message) {
		log(sender, DEBUG, message, null);
	}

	public static void debug(Object sender, String message, Throwable t) {
		log(sender, DEBUG, message, t);
	}

	public static boolean isDebugEnabledFor(Object sender) {
		return getLog(sender).isDebugEnabled();
	}

	public static boolean isInfoEnabledFor(Object sender) {
		return getLog(sender).isInfoEnabled();
	}

	public static Log getLog(Object sender) {
		Class<?> senderClass = sender instanceof Class ? (Class<?>) sender : sender.getClass();
		return LogFactory.getLog(senderClass);
	}
}